package com.wiscamp.ninechapters.problems.domain.models.problems.answers;

import com.wiscamp.ninechapters.common.core.ParseHelper;
import com.wiscamp.ninechapters.problems.math.LatexRadicalNumber;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 根数处理工具包
 */
public class RadicalNumberUtils {
    private static final Logger logger = LoggerFactory.getLogger(RadicalNumberUtils.class);

    public static final String RADICAL_NUMBER_PREFIX = "\\sqrt";

    public static final String SQUARE_ROOT_PREFIX = "\\sqrt[2]";

    private RadicalNumberUtils() {
    }

    public static LatexRadicalNumber toRadicalNumber(String text) {
        try {
            LatexRadicalNumber rootNumber = new LatexRadicalNumber();
            String latexText = text;
            if (!latexText.contains("[") && !latexText.contains("]")) {
                latexText = latexText.replace(RADICAL_NUMBER_PREFIX, SQUARE_ROOT_PREFIX);
            }

            if (latexText.startsWith("-")) {
                rootNumber.setSymbol("-");
                latexText = latexText.substring(1);
            }

            int index = latexText.indexOf(RADICAL_NUMBER_PREFIX);
            if (index >= 0) {
                String prefixNumberText = latexText.substring(0, index);
                if (!"".equals(prefixNumberText)) {
                    int prefixNumber = ParseHelper.parseInteger(prefixNumberText);
                    rootNumber.setPrefixNumber(prefixNumber);
                } else {
                    rootNumber.setPrefixNumber(0);
                }
                latexText = latexText.substring(index + 5);
                int beforeIndex = latexText.indexOf("[");
                int afterIndex = latexText.indexOf("]");
                if (index >= 0) {
                    String rootText = latexText.substring(index + 1, afterIndex - beforeIndex);
                    int root = Integer.parseInt(rootText);
                    rootNumber.setRoot(root);
                    latexText = latexText.substring(afterIndex + 1);
                }
                beforeIndex = latexText.indexOf("{");
                afterIndex = latexText.indexOf("}");
                String numberText = latexText.substring(beforeIndex + 1, afterIndex - beforeIndex);
                int number = Integer.parseInt(numberText);
                rootNumber.setNumber(number);
            }
            return rootNumber;
        } catch (Exception ex) {
            logger.error("Failed to convert radical number.", ex);
            return null;
        }
    }
}
